package com.zhentao.course.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.course.mapper.CoursesMapper;
import com.zhentao.course.pojo.Courses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课程管理控制器
 * 提供课程的增删改查功能
 */
@RestController
@RequestMapping("/courses")
@CrossOrigin(origins = "*")
public class CourseController {

    @Autowired
    private CoursesMapper coursesMapper;

    /**
     * 新增课程
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createCourse(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 参数校验
            String title = (String) request.get("title");
            if (title == null || title.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "课程标题不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 创建课程对象
            Courses course = new Courses();
            course.setTitle(title);
            
            // 设置教师ID
            if (request.get("teacherId") != null) {
                course.setTeacherId(Long.valueOf(request.get("teacherId").toString()));
            }
            
            // 设置分类ID
            if (request.get("categoryId") != null) {
                course.setCategoryId(Integer.valueOf(request.get("categoryId").toString()));
            }
            
            // 设置课程描述
            if (request.get("description") != null) {
                course.setDescription((String) request.get("description"));
            }
            
            // 设置课程封面
            if (request.get("coverImage") != null) {
                course.setCoverImage((String) request.get("coverImage"));
            }
            
            // 设置课程价格
            if (request.get("price") != null) {
                course.setPrice(new BigDecimal(request.get("price").toString()));
            }
            
            // 设置难度级别
            if (request.get("difficultyLevel") != null) {
                course.setDifficultyLevel(Integer.valueOf(request.get("difficultyLevel").toString()));
            }
            
            // 设置课程状态，默认为草稿状态
            if (request.get("status") != null) {
                course.setStatus(Integer.valueOf(request.get("status").toString()));
            } else {
                course.setStatus(0); // 默认草稿状态
            }
            
            // 设置标签
            if (request.get("tags") != null) {
                course.setTags((String) request.get("tags"));
            }
            
            // 设置创建时间
            course.setCreatedAt(new Date());
            
            // 保存到数据库
            int result = coursesMapper.insert(course);
            
            if (result > 0) {
                response.put("success", true);
                response.put("message", "课程创建成功");
                response.put("course", course);
            } else {
                response.put("success", false);
                response.put("message", "课程创建失败");
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 根据ID获取课程详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getCourseById(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Courses course = coursesMapper.selectById(id);
            
            if (course != null) {
                response.put("success", true);
                response.put("course", course);
            } else {
                response.put("success", false);
                response.put("message", "课程不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取课程列表（支持分页和条件查询）
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getCourses(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) Long teacherId,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) Integer status) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 创建分页对象
            Page<Courses> pageObj = new Page<>(page, size);
            
            // 创建查询条件
            QueryWrapper<Courses> queryWrapper = new QueryWrapper<>();
            
            // 根据标题模糊查询
            if (title != null && !title.trim().isEmpty()) {
                queryWrapper.like("title", title);
            }
            
            // 根据教师ID查询
            if (teacherId != null) {
                queryWrapper.eq("teacher_id", teacherId);
            }
            
            // 根据分类ID查询
            if (categoryId != null) {
                queryWrapper.eq("category_id", categoryId);
            }
            
            // 根据状态查询
            if (status != null) {
                queryWrapper.eq("status", status);
            }
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc("created_at");
            
            // 执行分页查询
            IPage<Courses> pageResult = coursesMapper.selectPage(pageObj, queryWrapper);
            
            response.put("success", true);
            response.put("courses", pageResult.getRecords());
            response.put("total", pageResult.getTotal());
            response.put("pages", pageResult.getPages());
            response.put("current", pageResult.getCurrent());
            response.put("size", pageResult.getSize());
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 修改课程信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateCourse(@PathVariable Long id, @RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 检查课程是否存在
            Courses existingCourse = coursesMapper.selectById(id);
            if (existingCourse == null) {
                response.put("success", false);
                response.put("message", "课程不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 更新课程信息
            if (request.get("title") != null) {
                String title = (String) request.get("title");
                if (title.trim().isEmpty()) {
                    response.put("success", false);
                    response.put("message", "课程标题不能为空");
                    return ResponseEntity.badRequest().body(response);
                }
                existingCourse.setTitle(title);
            }
            
            if (request.get("teacherId") != null) {
                existingCourse.setTeacherId(Long.valueOf(request.get("teacherId").toString()));
            }
            
            if (request.get("categoryId") != null) {
                existingCourse.setCategoryId(Integer.valueOf(request.get("categoryId").toString()));
            }
            
            if (request.get("description") != null) {
                existingCourse.setDescription((String) request.get("description"));
            }
            
            if (request.get("coverImage") != null) {
                existingCourse.setCoverImage((String) request.get("coverImage"));
            }
            
            if (request.get("price") != null) {
                existingCourse.setPrice(new BigDecimal(request.get("price").toString()));
            }
            
            if (request.get("difficultyLevel") != null) {
                existingCourse.setDifficultyLevel(Integer.valueOf(request.get("difficultyLevel").toString()));
            }
            
            if (request.get("status") != null) {
                existingCourse.setStatus(Integer.valueOf(request.get("status").toString()));
            }
            
            if (request.get("tags") != null) {
                existingCourse.setTags((String) request.get("tags"));
            }
            
            // 执行更新
            int result = coursesMapper.updateById(existingCourse);
            
            if (result > 0) {
                response.put("success", true);
                response.put("message", "课程更新成功");
                response.put("course", existingCourse);
            } else {
                response.put("success", false);
                response.put("message", "课程更新失败");
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 删除课程
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteCourse(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 检查课程是否存在
            Courses course = coursesMapper.selectById(id);
            if (course == null) {
                response.put("success", false);
                response.put("message", "课程不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 执行删除
            int result = coursesMapper.deleteById(id);
            
            if (result > 0) {
                response.put("success", true);
                response.put("message", "课程删除成功");
            } else {
                response.put("success", false);
                response.put("message", "课程删除失败");
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 批量删除课程
     */
    @DeleteMapping("/batch")
    public ResponseEntity<Map<String, Object>> deleteCoursesBatch(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            @SuppressWarnings("unchecked")
            List<Long> ids = (List<Long>) request.get("ids");
            
            if (ids == null || ids.isEmpty()) {
                response.put("success", false);
                response.put("message", "请选择要删除的课程");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 执行批量删除
            int result = coursesMapper.deleteBatchIds(ids);
            
            response.put("success", true);
            response.put("message", "成功删除 " + result + " 门课程");
            response.put("deletedCount", result);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 根据教师ID获取课程列表
     */
    @GetMapping("/teacher/{teacherId}")
    public ResponseEntity<Map<String, Object>> getCoursesByTeacher(@PathVariable Long teacherId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            QueryWrapper<Courses> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("teacher_id", teacherId);
            queryWrapper.orderByDesc("created_at");
            
            List<Courses> courses = coursesMapper.selectList(queryWrapper);
            
            response.put("success", true);
            response.put("courses", courses);
            response.put("count", courses.size());
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 根据分类ID获取课程列表
     */
    @GetMapping("/category/{categoryId}")
    public ResponseEntity<Map<String, Object>> getCoursesByCategory(@PathVariable Integer categoryId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            QueryWrapper<Courses> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("category_id", categoryId);
            queryWrapper.eq("status", 1); // 只查询已发布的课程
            queryWrapper.orderByDesc("created_at");
            
            List<Courses> courses = coursesMapper.selectList(queryWrapper);
            
            response.put("success", true);
            response.put("courses", courses);
            response.put("count", courses.size());
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
        
        return ResponseEntity.ok(response);
    }
}